import React, { Component } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import { Card, Tabs, Upload, Button, Form, Modal, Input, Icon, message, Select } from 'antd';
import styles from './index.less';
import Tiptap from './Tiptap';
import { postSaveTemplate } from '@/services/modelInstruction';

class AddInstructions extends Component {
    constructor(props) {
        super(props);
        this.state = {
            imgUrl: "",
            loading: false,
            instructInfo: null,
            instructVisible: false,
            defaultContent: '',
            defaultImgUrl: [
                { id: 'U01', url: '/preSetImg/directory.png' },
                { id: 'U02', url: '/preSetImg/game.png' },
                { id: 'U03', url: '/preSetImg/information.png' },
                { id: 'U04', url: '/preSetImg/inspiration.png' },
                { id: 'U05', url: '/preSetImg/lineGraph.png' },
                { id: 'U06', url: '/preSetImg/opinion.png' },
                { id: 'U07', url: '/preSetImg/tag.png' },
                { id: 'U08', url: '/preSetImg/target.png' },
                { id: 'U09', url: '/preSetImg/text.png' },
                { id: 'U10', url: '/preSetImg/time.png' },
            ]
        };
        this.ProsemirrorEditorRef = React.createRef();
    }

    componentDidMount() {
        if (this.props.onRef) {
            this.props.onRef(this)
        }
    }

    _init_ = row => {
        let content = (`<p>${formatMessage({ id: 'personalizedInstructionLibrary.copywriterPrompt' })}</p><p>${formatMessage({ id: 'personalizedInstructionLibrary.copySubject' })}：<span data-type="spannode">&nbsp;传承与创新：桂花手表的故事</span><span>&nbsp;</span></p><p>${formatMessage({ id: 'personalizedInstructionLibrary.content' })}：<span data-type="spannode">&nbsp;结合桂花手表的历史背景和现代设计，撰写引人入胜的故事</span><span>&nbsp;</span></p>`);
        if (row && row.content) {
            content = row.content.replace(/<span class="editor-input">/gi, "<span class='editor-input' data-type='spannode'>")
        };
        this.setState({
            instructVisible: true,
            instructInfo: row,
            imgUrl: row && row.imgUrl ? row.imgUrl : '',
            defaultContent: content,
        })
    }

    instructCancel = () => {
        this.setState({
            imgUrl: "",
            instructInfo: null,
            instructVisible: false,
            defaultContent: '',
        })
    }

    instructSubmit = e => {
		e.preventDefault();
        const { imgUrl, instructInfo } = this.state;
        const { form } = this.props;
        let content, obj;
        if (this.ProsemirrorEditorRef) {
            content = this.ProsemirrorEditorRef.current.getHtml();
            // console.log(content);
        };
        let formInfo = form.getFieldsValue();
        // console.log(formInfo);

        form.validateFields(async (err, values) => {
            obj = {
                title: formInfo?.instructName,
                content,
                type: 0,
                id: instructInfo?.id,
                categoryId: formInfo?.instructCategory,
                // tagIdList: formInfo?.instructTag,
            };
            if (imgUrl && imgUrl !== '') {
                obj.imgUrl = imgUrl;
            } else {
                form.setFields({ 
                    imgUrl: {
                        errors: [new Error(formatMessage({ id: 'personalizedInstructionLibrary.imageRequired' }))],
                    }
                });
                return;
            };
            let res = await postSaveTemplate(obj);
            console.log(res);
            if (res.code === 0) {
                this.props.getList();
                this.instructCancel();
                message.success(formatMessage({ id: 'personalizedInstructionLibrary.operationSuccess' }));
            }
        })
    }

    render() {
        const { instructVisible, defaultContent, instructInfo, imgUrl, defaultImgUrl } = this.state;
        const { categoryList, tagList, categoryId } = this.props;
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        const uploadButton = (
            <div
                style={{
                    border: '#E8E8E8 1px solid',
                    padding: '14px 7px',
                    textAlign: 'center',
                    background: '#FAFAFA',
                }}
            >
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">{formatMessage({ id: 'personalizedInstructionLibrary.uploadFile' })}</div>
            </div>
        );

        return (
            <Modal
                title={formatMessage({ id: 'personalizedInstructionLibrary.add' })}
                onCancel={this.instructCancel}
                visible={instructVisible}
                footer={[
                    <Button onClick={this.instructCancel}>{formatMessage({ id: 'personalizedInstructionLibrary.cancel' })}</Button>,
                    <Button type="primary" onClick={this.instructSubmit}>{formatMessage({ id: 'personalizedInstructionLibrary.confirm' })}</Button>
                ]}
                width={'800px'}
                destroyOnClose
            >
                <Form {...formItemLayout}>
                    <Form.Item label={formatMessage({ id: 'personalizedInstructionLibrary.name' })}>
                        {getFieldDecorator('instructName', {
                            initialValue: instructInfo?.title,
                            rules: [{ required: true, message: formatMessage({ id: 'personalizedInstructionLibrary.pleaseEnterName' })}],
                        })(<Input placeholder={formatMessage({ id: 'personalizedInstructionLibrary.pleaseEnterName' })} />)}
                    </Form.Item>

                    <Form.Item label={formatMessage({ id: 'personalizedInstructionLibrary.category' })}>
                        {getFieldDecorator('instructCategory', {
                            initialValue: instructInfo ? instructInfo.categoryId : categoryId && categoryId !== '' ? categoryId : undefined,
                            rules: [{ required: true, message: formatMessage({ id: 'personalizedInstructionLibrary.categoryRequired' })}],
                        })(
                            <Select placeholder={formatMessage({ id: 'personalizedInstructionLibrary.selectCategory' })}>
                                {categoryList && categoryList.length > 0 && categoryList.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                    );
                                })}
                            </Select>
                        )}
                    </Form.Item>

                    <Form.Item label={formatMessage({ id: 'personalizedInstructionLibrary.icon' })}>
                        <span className={styles['default-img-ul']}>
                            {defaultImgUrl && defaultImgUrl.length > 0 && defaultImgUrl.map((j, k) => {
                                return (
                                    <span
                                        key={k}
                                        className={`${styles['default-img-li']} ${imgUrl === j.url ? styles['default-img-li-active'] : ''}`}
                                        onClick={() => this.setImgUrl(j, "imgUrl")}
                                    >
                                        <img src={j.url} width="36" height="36" />
                                    </span>
                                )
                            })}
                            {getFieldDecorator("imgUrl", {
                                valuePropName: "url",
                                getValueFromEvent: this.normFile
                            })(
                                <Upload
                                    name='file'
                                    listType='picture'
                                    showUploadList={false}
                                    action='/cloud/file/upload'
                                    beforeUpload={this.beforeUpload}
                                    onChange={(info) => this.handleChangeImage(info, "imgUrl")}
                                    accept='.png,.jpg'
                                >
                                    {imgUrl && imgUrl !== '' ? (
                                        defaultImgUrl && defaultImgUrl.length > 0 ? (
                                            defaultImgUrl.map(f => f.url).indexOf(imgUrl) < 0 ? (
                                                <div
                                                    style={{
                                                        width: '72px',
                                                        height: '72px',
                                                        fontSize: '0px',
                                                        lineHeight: '72px',
                                                        textAlign: 'center',
                                                        border: '#3e5bff 1px solid',
                                                        background: '#f0f5ff',
                                                    }}
                                                >
                                                    <img src={fileUrl + imgUrl} alt='file' style={{ maxWidth: 70, maxHeight: 70 }} />
                                                </div>
                                            ) : uploadButton
                                        ) : (
                                            <div
                                                style={{
                                                    width: '72px',
                                                    height: '72px',
                                                    fontSize: '0px',
                                                    lineHeight: '72px',
                                                    textAlign: 'center',
                                                    border: '#3e5bff 1px solid',
                                                    background: '#f0f5ff',
                                                }}
                                            >
                                                <img src={fileUrl + imgUrl} alt='file' style={{ maxWidth: 70, maxHeight: 70 }} />
                                            </div>
                                        )
                                    ) : uploadButton}
                                </Upload>
                            )}
                        </span>
                    </Form.Item>

                    <Form.Item label={formatMessage({ id: 'personalizedInstructionLibrary.content' })} className={styles['editor']}>
                        <Tiptap ref={this.ProsemirrorEditorRef} content={defaultContent} />
                    </Form.Item>

                    {/* <Form.Item label="指令标签">
                        {getFieldDecorator('instructTag', {
                            initialValue: instructInfo?.tagIdList
                        })(
                            <Select placeholder="选择指令标签（多选）" mode="multiple">
                                {tagList && tagList.length > 0 && tagList.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                    );
                                })}
                            </Select>
                        )}
                    </Form.Item> */}

                </Form>
            </Modal >
        );
    }

    normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };

    handleChangeImage = (file, type) => {
        if (file.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        };
        if (file.file.status === "done") {
            this.setState({
                [type]: file.file.response.url,
                loading: false,
            });
        }
    };

    /**
     * 上传图片前判断
     * @returns {*}
     */
    beforeUpload = (file) => {
        let b = /\.(png|jpg|gif)$/;
        let a = file.name.toLowerCase();

        const pig = b.test(a);
        const isJPG = file.type;
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!pig) {
            if (!isLt2M) {
                message.error(formatMessage({ id: 'personalizedInstructionLibrary.imageSizeLimit' }));
            } else {
                message.error(formatMessage({ id: 'personalizedInstructionLibrary.imageFormatError' }));
            }
        } else {
            if (!isLt2M) {
                message.error("请上传小于2M的图片");
            }
        };
        return isJPG && isLt2M && pig;
    };

    setImgUrl = (row, type) => {
        this.setState({ [type]: row.url });
    }

}

export default Form.create()(AddInstructions);
